package com.jstyle.jclife.activity;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.jstyle.jclife.NetWork.NetWorkException;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.ActionData;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.model.UserInfo;

import com.jstyle.jclife.model.UserInfoQuery;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SHA1;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.EditTextWithDelete;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.tv_login_title)
    TextView tvLoginTitle;
    @BindView(R.id.edit_login_email)
    EditTextWithDelete editLoginEmail;
    @BindView(R.id.edit_login_pwd)
    EditTextWithDelete editLoginPwd;
    @BindView(R.id.bt_login_back)
    Button btLoginBack;
    @BindView(R.id.bt_login_login)
    Button btLoginLogin;
    @BindView(R.id.tv_toFindPsd)
    TextView tvToFindPsd;
    private Disposable loginDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        tvToFindPsd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG| Paint.ANTI_ALIAS_FLAG);
    }

    @OnClick({R.id.bt_login_back, R.id.bt_login_login, R.id.tv_toFindPsd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_login_back:
                finish();
                break;
            case R.id.bt_login_login:
                toLogin();
                break;
            case R.id.tv_toFindPsd:
                startActivity(ForgotPwdActivity.class);
                break;
        }
    }

    private void toLogin() {
        String email=editLoginEmail.getText().toString();
        String pwd=editLoginPwd.getText().toString();
        if ( TextUtils.isEmpty(email) || TextUtils.isEmpty(pwd)) {
            showToast(getString(R.string.fill_all_info));
            return;
        }
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(NetWorkConast.KEY_userEmail, email);
        map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(pwd));
      //  map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(pwd));
        showProgressDialog(getString(R.string.login_login));
        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi()
                .login(map)
                .flatMap(new Function<NetResultData<String>, ObservableSource<NetResultData<UserInfoQuery>>>() {
            @Override
            public ObservableSource<NetResultData<UserInfoQuery>> apply(NetResultData<String> netResultData) throws Exception {
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode,LoginActivity.this);
                if (msgCode == NetResultData.Success_Code) {
                    saveUserInfo(netResultData.getData());
                    return NetWorkUtil.getInstance()
                            .getJstyleApi()
                            .getUserInfo(netResultData.getData());
                } else {
                    throw new NetWorkException(msg);
                }
            }
        }).compose(SchedulersTransformer.<NetResultData<UserInfoQuery>>io2MainObservable()).subscribe(new Observer<NetResultData<UserInfoQuery>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData<UserInfoQuery> value) {
                disMissProgressDialog();
                int msgCode = value.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode, LoginActivity.this);
                if (msgCode == NetResultData.Success_Code) {
                    SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN,true);
                    if (value.getData() != null) {
                        updateUserInfo(value.getData());
                    }
                  startActivity();

                    finish();
                    RxBus.getInstance().sendAction(ActionData.FinishLoginIn);
                    return;
                } else if (msgCode == NetResultData.Failed_Code) {
                    msg = getResources().getString(R.string.login_loginfailed);
                }
              //  showToast(msg);
            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
                showToast(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }
    private void updateUserInfo(UserInfoQuery data) {
        String uid=this.uid;
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid + "");
        int age=25;
        if (!TextUtils.isEmpty(data.getBirthday())) {
            String[]birthdayArray=data.getBirthday().split("-");
            int year= Integer.parseInt(birthdayArray[0]);
            Calendar calendar=Calendar.getInstance();
            int nowYear=calendar.get(Calendar.YEAR);
            age = nowYear-year;
        }
        String gender=data.getGender();
        if(TextUtils.isEmpty(gender)){
            gender="male";
        }
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(uid + "");
            userInfo.setAge(age);
            userInfo.setIconPath(data.getAvatar());
            userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            userInfo.setName(data.getNickname());
            userInfo.setWeight(data.getWeight());
            userInfo.setGender(gender.equals("male") ? 0 : 1);
            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setUserId(uid + "");
            userInfo.setAge(age);
            if(!TextUtils.isEmpty(data.getBirthday())) userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            if(!TextUtils.isEmpty(data.getNickname()))userInfo.setName(data.getNickname());
            userInfo.setWeight(data.getWeight());
            userInfo.setGender(gender.equals("male") ? 0 : 1);
            userInfo.setIconPath(data.getAvatar());
            UserInfoDaoManager.updateUser(userInfo);
        }
        downLoadIcon(data.getAvatar(),uid);
    }
    String uid;
    private void saveUserInfo(String id) {
        uid=id;
        String phone = editLoginEmail.getText().toString();
        String psd = editLoginPwd.getText().toString();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(id);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);

            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            UserInfoDaoManager.updateUser(userInfo);
        }
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, phone);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, psd);

    }

    private void startActivity(){
        boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
        if(isFirst){
            startActivity(BindDeviceActivity.class);
        }else{
            List<BindDeviceInfo> bindDeviceInfoList= BindDeviceInfoDaoManager.queryAllData();
            Class next=null;
            if(bindDeviceInfoList.size()!=0){
                UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid + "");
                String iconPath=userInfo.getIconPath();
                next=TextUtils.isEmpty(iconPath) ? UserInfoSettingActivity.class : MainActivity.class;
            }else{
                next=BindDeviceActivity.class;
            }
            startActivity(next,SharedPreferenceUtils.KEY_From_Login,true);
        }

    }
    private static final String TAG = "LoginActivity";
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(loginDisposable);
    }

    private void downLoadIcon(String headUrl,final String uid){
        if(headUrl==null)return;
     NetWorkUtil.getInstance().getJstyleApi().downloadIcon(headUrl).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<ResponseBody>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(ResponseBody value) {

            try {
                writeToDisk(value,uid);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Throwable e) {
            Log.i(TAG, "onError: " + e.getMessage());
        }

        @Override
        public void onComplete() {


        }
    });
}

    private void writeToDisk(ResponseBody responseBody,final  String uid) throws IOException {
        File file = new File(ImageUtils.headPath);
        File fileIcon = new File(ImageUtils.headPath + ImageUtils.md5Encoder(uid));
        Log.i(TAG, "writeToDisk: " + ImageUtils.md5Encoder(NetWorkUtil.getUserId()));
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileIcon.exists() && fileIcon.length() == responseBody.contentLength()) {
            // finishLogin();
            return;
        }
        byte[] buffer = new byte[1024 * 8];
        int len;
        FileOutputStream out = new FileOutputStream(fileIcon);
        InputStream in = responseBody.byteStream();
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        //  finishLogin();
    }
}
